package com.xykj.initial.controller;

import cn.hutool.core.util.StrUtil;
import com.xykj.initial.common.Result;
import com.xykj.initial.entity.Account;
import com.xykj.initial.service.AdminService;
import com.xykj.initial.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/home")
public class HomeController {

    @Resource
    private UserService userService;

    @Resource
    private AdminService adminService;

    // 登陆
    @PostMapping("/login")
    public Result login(@RequestBody Account account) {
        if (StrUtil.isEmpty(account.getUsername()) || StrUtil.isEmpty(account.getPassword())) {
            return Result.error("605", "用户名或者密码不能为空");
        }

        if (StrUtil.equals(account.getRole(), "ROLE_USER")) {
            account = userService.login(account);
        }
        if (StrUtil.equals(account.getRole(), "ROLE_ADMIN")) {
            account = adminService.login(account);
        }
        return Result.success(account);
    }

    // 注册
    @PostMapping("/register")
    public Result register(@RequestBody Account account) {
        if (StrUtil.isEmpty(account.getUsername()) || StrUtil.isEmpty(account.getPassword())) {
            return Result.error("605", "用户名或者密码不能为空");
        }

        if (StrUtil.equals(account.getRole(), "ROLE_USER")) {
            userService.register(account);
        }
        if (StrUtil.equals(account.getRole(), "ROLE_ADMIN")) {
            adminService.register(account);
        }
        return Result.success();
    }
}
